package billrestauration.controllers;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import billrestauration.util.MimeUtil;
import billrestauration.util.Util;
@Controller
public class RessourceController {
	@Value("${upload.path}")
	  String ressourcepath;
	@RequestMapping(value="/static/resources/{name}")
	public void treatment(@PathVariable(value="name")String resourcename,
			HttpServletRequest request, HttpServletResponse response) throws IOException{
		String path= Util.currentDir();
		if(!path.endsWith(File.separator))
			path+=File.separator;
		path+=resourcename;
		File r=new File(path);
		if(!r.exists()||!r.isFile()){
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);
		}else{
			response.setContentType(new MimeUtil().getMimeType(r));
 
	         response.setHeader("Content-disposition","attachment; filename="+r.getName()+"");
	         response.setContentLength((int) r.length());
	         OutputStream out = response.getOutputStream();
	         FileInputStream in = new FileInputStream(r);
	         byte[] buffer = new byte[4096];
	         int length;
	         while ((length = in.read(buffer)) > 0){
	            out.write(buffer, 0, length);
	            System.out.println(length+" octets read and put to outpout");
	         }
	         in.close();
	         out.flush();
		}
		
			
	}
}
